package com.android.lovepick.util;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo.State;
import android.os.Build;
import android.provider.Settings;
import android.util.Log;
import android.widget.Toast;

/**
 * @author Liutong
 */
public class BaseUtils
{
	private static final String BASE_TAG = "BaseUtils";

	public interface DialogClickListener
	{
		public void doPositiveClick();

		public void doNegativeClick();
	}

	public static void exit(Activity activity)
	{
		activity.finish();
	}

	@SuppressLint("NewApi")
	public static void setUpActionBar(Activity activity)
	{
		// Make sure we're running on Honeycomb or higher to use ActionBar APIs
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
		{
			ActionBar actionBar = activity.getActionBar();
			actionBar.setDisplayHomeAsUpEnabled(true);
		}
	}

	public static void showToast(Context context, String message)
	{
		Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
	}

	public static void showToast(Context context, int resId)
	{
		// TODO Auto-generated method stub
		Toast.makeText(context, resId, Toast.LENGTH_SHORT).show();
	}

	public static void showAlertDialog2(Context context, String title,
			String content, String positive, String negative,
			final DialogClickListener listener)
	{
		AlertDialog.Builder builder = new AlertDialog.Builder(context);
		builder.setTitle(title);
		builder.setMessage(content);
		builder.setPositiveButton(positive,
				new DialogInterface.OnClickListener()
				{

					public void onClick(DialogInterface dialog, int which)
					{
						// TODO Auto-generated method stub
						listener.doPositiveClick();
					}
				});
		builder.setNegativeButton(negative,
				new DialogInterface.OnClickListener()
				{

					public void onClick(DialogInterface dialog, int which)
					{
						// TODO Auto-generated method stub
						listener.doNegativeClick();
					}
				});
		AlertDialog dialog = builder.create();
		dialog.show();
	}

	/**
	 * 检测系统网络状态
	 * 
	 * @param context
	 * @return 移动或WIFI其中之一开启则返回true, 二者均关闭则返回false.
	 */
	public static boolean checkNetwork(Context context)
	{
		boolean status = false;
		ConnectivityManager manager = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);

		State mobile = manager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE)
				.getState();
		Log.i(BASE_TAG, "mobile network:" + mobile.toString());
		State wifi = manager.getNetworkInfo(ConnectivityManager.TYPE_WIFI)
				.getState();
		Log.i(BASE_TAG, "WIFI network:" + wifi.toString());

		if (mobile.equals(State.CONNECTED) || wifi.equals(State.CONNECTED))
		{
			status = true;
		}
		else if (mobile.equals(State.DISCONNECTED)
				&& wifi.equals(State.DISCONNECTED))
		{
			status = false;
		}
		else
		{
			status = false;
		}

		return status;
	}

	/**
	 * 检测系统GPS状态
	 * 
	 * @param context
	 * @return GPS开启返回true, 关闭则返回false.
	 */
	public static boolean checkGPS(Context context)
	{
		boolean gpsStatus = Settings.Secure.isLocationProviderEnabled(
				context.getContentResolver(), LocationManager.GPS_PROVIDER);
		Log.i(BASE_TAG, "GPS:" + String.valueOf(gpsStatus));

		return gpsStatus;
	}

	/**
	 * 根据给定的格式检测字符串是否是符合该格式的日期时间
	 * 
	 * @param date 待检测日期时间字符串
	 * @param format 检测格式
	 * @return 符合检测格式返回true, 否则false.
	 */
	public static boolean checkDate(String date, String pattern)
	{
		SimpleDateFormat dateFormat = new SimpleDateFormat(pattern);
		dateFormat.setLenient(false);
		try
		{
			dateFormat.parse(date);
			return true;
		}
		catch (Exception e)
		{
			// TODO: handle exception
			Log.i(BASE_TAG, "checkDate:" + e.getMessage());
			return false;
		}
	}

	/**
	 * 检测给定字符串是否符合Email格式
	 * 
	 * @param email 待检测字符串
	 * @return 符合Email格式返回true, 否则false.
	 */
	public static boolean checkEmail(String email)
	{
		Pattern pattern = Pattern.compile(Constant.REGE_EMAIL);
		Matcher matcher = pattern.matcher(email);
		return matcher.matches();
	}

	/**
	 * 检测给定字符串是否为手机电话号码
	 * 
	 * @param mobileNum 待检测字符串
	 * @return 为手机号码返回true, 否则false.
	 */
	public static boolean checkMobileNum(String mobileNum)
	{
		Pattern pattern = Pattern.compile(Constant.REGE_MOBILENUM);
		Matcher matcher = pattern.matcher(mobileNum);
		return matcher.matches();
	}

	/**
	 * Check whether the specified string is a numeric.
	 * 
	 * @param num string that need to be checked.
	 * @return true if the string is a numeric, false otherwise.
	 */
	public static boolean checkNumeric(String num)
	{
		try
		{
			Integer.parseInt(num);
			return true;
		}
		catch (Exception e)
		{
			// TODO: handle exception
			Log.i(BASE_TAG, "checkNumeric:" + e.getMessage());
			return false;
		}
	}

	/**
	 * 判断给定字符串是否空白串. 空白串是指由空格、制表符、回车符、换行符组成的字符串.
	 * 
	 * @param input 待检测字符串
	 * @return boolean 若输入字符串为null或空字符串，返回true
	 */
	public static boolean checkEmptyString(String input)
	{
		if ((input == null) || "".equals(input))
		{
			return true;
		}

		for (int i = 0; i < input.length(); i++)
		{
			char c = input.charAt(i);
			if ((c != ' ') && (c != '\t') && (c != '\r') && (c != '\n'))
			{
				return false;
			}
		}
		return true;
	}

	/**
	 * 解析从服务器返回的订单数据JSON字符串
	 * 
	 * @param jsonString 待解析的json字符串
	 * @return
	 *         <ul>
	 *         <li>解析成功返回一个List对象, List中的项为订单内容, 由键值对组成;</li>
	 *         <li>解析失败则返回null.</li>
	 *         </ul>
	 */
	public static List<Map<String, String>> parseJsonFromString(
			String jsonString)
	{
		List<Map<String, String>> list = null;
		try
		{
			Log.i(BASE_TAG, "解析JSON数据-jsonString: " + jsonString);
			list = new ArrayList<Map<String, String>>();
			JSONArray jsonArray = new JSONArray(jsonString);
			for (int i = 0; i < jsonArray.length(); i++)
			{
				Map<String, String> map = new HashMap<String, String>();
				JSONObject jsonObject = jsonArray.getJSONObject(i);
				map.put("orderID", jsonObject.getString("orderID"));
				map.put("nickName", jsonObject.getString("nickName"));
				map.put("goTime", jsonObject.getString("goTime"));
				map.put("src", jsonObject.getString("src"));
				map.put("slat", jsonObject.getString("slat"));
				map.put("slng", jsonObject.getString("slng"));
				map.put("dest", jsonObject.getString("dest"));
				map.put("dlat", jsonObject.getString("dlat"));
				map.put("dlng", jsonObject.getString("dlng"));
				map.put("money", jsonObject.getString("money"));
				map.put("state", jsonObject.getString("state"));
				Log.i(BASE_TAG, map.toString());
				list.add(map);
			}
			Log.i(BASE_TAG, "---list info---");
			Log.i(BASE_TAG, list.toString());
		}
		catch (JSONException e)
		{
			// TODO Auto-generated catch block
			list = null;
			e.printStackTrace();

		}
		return list;
	}

	/**
	 * 获取系统当前时间
	 * 
	 * @return 返回当前系统时间对应的字符串(yyyy-MM-dd hh:mm:ss)
	 */
	public static String getCurrentDate()
	{
		Calendar c = Calendar.getInstance();

		String year = String.valueOf(c.get(Calendar.YEAR));
		String month = String.valueOf(c.get(Calendar.MONTH));
		String day = String.valueOf(c.get(Calendar.DAY_OF_MONTH) + 1);
		String hour = String.valueOf(c.get(Calendar.HOUR_OF_DAY));
		String mins = String.valueOf(c.get(Calendar.MINUTE));
		String secs = String.valueOf(c.get(Calendar.SECOND));

		StringBuffer stringBuffer = new StringBuffer();
		stringBuffer.append(year + "-" + month + "-" + day + " " + hour + ":"
				+ mins + ":" + secs);

		return stringBuffer.toString();
	}
}
